package com.leetcode.search.bfs;

import com.leetcode.basic.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author Dennis Li
 * @date 2020/7/25 20:33
 */
public class RightSideView_199 {

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                if (node.left != null){
                    queue.offer(root.left);
                }
                if (node.right != null){
                    queue.offer(root.right);
                }
                if (size == 0) {
                    // 后入后出，所以要让右节点在后面入队，保证最后出队的一定是在最右边的节点
                    list.add(node.val);
                }
            }
        }
        return list;
    }

}
